﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Helpers
{
    public class CmdHelper
    {
        public static Process Start(string fileName, string arguments, bool createNoWindow = false, bool redirectStandardInput = false, bool redirectStandardOutput = false, bool redirectStandardError = false,string workingDirectory=null)
        {
            ProcessStartInfo psi = new ProcessStartInfo
            {
                FileName = fileName,
                Arguments = arguments,
                UseShellExecute = false,//true-不支持重定向输入和输出,
                CreateNoWindow = createNoWindow,//是否显示窗口
                RedirectStandardInput = redirectStandardInput,
                RedirectStandardOutput = redirectStandardOutput,
                RedirectStandardError = redirectStandardError,
                WorkingDirectory = workingDirectory,
            };
            var process = Process.Start(psi);
            return process;
        }

        /// <summary>
        /// 运行程序
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="arguments">参数</param>
        /// <returns></returns>
        public static async Task<string> RunCmd(string fileName, string arguments, bool createNoWindow = false)
        {
            ProcessStartInfo start = new ProcessStartInfo
            {
                FileName = fileName,
                Arguments = arguments,
                UseShellExecute = false,          // Do not use OS shell
                CreateNoWindow = createNoWindow,            // We don't need new window
                RedirectStandardOutput = true,    // Any output, generated by application will be redirected back
                RedirectStandardError = true     // Any error in standard output will be redirected back (for example exceptions)
            };

            using (Process process = Process.Start(start))
            {
                string result = await process.StandardError.ReadToEndAsync();
                if (string.IsNullOrEmpty(result))
                {
                    result = await process.StandardOutput.ReadToEndAsync();
                }
                process.WaitForExit();
                return result;
            }
        }
    }
}
